<?php
/**
 * 日志格式化
 * @文件名称: Trace.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\lib;
use Yii;
use yii\base\ErrorException;
class  Trace
{
    /**
     * 将里面的元素都转化成字符串.
     **/
    public static function toStr($context)
    {
        try {
            foreach ($context as $key => $value) {
                if (is_array($value)) {
                    $context[$key] = self::toStr($value);
                } else {
                    $context[$key] = "'" . ($value) . "'";
                    //$context[$key] = strval($value);
                    //$context[$key] = strval($value);
                }
            }
        } catch (\ErrorException $e) {
            Yii::error(['msg' => $e->getMessage(), 'context' => "'" . json_encode($context) . "'"], 'trace_parse_error') ;
        }
        return $context;
    }
    /**
     *  记录追踪日志.
     *  @param  $message  string  记录的事件名字
     *  @param  $security string  事件的级别
     *  @param  $context  array  上下文
     *  @param  $category string  访问的路径
     **/
    public static function addLog($message, $security, $context = array(), $category = 'default')
    {
        if ($category == 'default') {   
            $category = Yii::$app->controller->id . '-' . Yii::$app->controller->action->id;
        }
        // 定义trackid , 方便跟踪请求日志链条
        defined('YII_TRACK_ID') or define('YII_TRACK_ID', md5(microtime(True) . rand(0, 10000)));
        $info = [ 
            'trackid' => YII_TRACK_ID,
			'@timestamp' => date('Y-m-d H:i:s'),
            '@message' => $message,
            'server' => gethostname(),
            'context' => $context,
            //'context' => self::toStr($context),
            'level' => $security,
        ];  
        $category = 'activity-' . $category;
        defined("LOGFILE") OR define('LOGFILE', "/data/logs/" . date("md") . '_trace_group.txt');
        if (!file_exists(LOGFILE)) {
		    file_put_contents(LOGFILE, json_encode($info , JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND | LOCK_EX);
            chmod(LOGFILE, 0766);
        } else {
		    file_put_contents(LOGFILE, json_encode($info , JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND | LOCK_EX);
        }
        $info['context'] = self::toStr($context);

        if ($security == 'info') {   
            Yii::info($info, $category);
        } elseif ($security == 'warning') {   
            Yii::warning($info, $category);
        } elseif ($security == 'error') {   
            Yii::error($info, $category);
        } else {
            //添加日志
            Yii::trace($info, $category);
        }   
        return True;
    }
}
